<script setup lang="ts">
import { onMounted, ref, onBeforeUnmount, watch, nextTick } from "vue"

defineOptions({ name: 'CustomPopover' })
const props = defineProps({
  strTxt: {
    type: String as any,
    required: true
  }
});

const customPopover = ref()
const isOverflowHidden = ref(false)
const tooltipWidth = ref(200)

const checkOverflow = () => {
  const el = customPopover.value
  if (el) {
    tooltipWidth.value = el?.clientWidth
    isOverflowHidden.value = !(el?.scrollWidth > el?.clientWidth)
  } else {
    isOverflowHidden.value = false
  }
}

// 监听文本内容变化
watch(() => props.strTxt, async () => {
  // 等待 DOM 更新后再检查溢出
  await nextTick()
  checkOverflow()
}, { immediate: true })

onMounted(() => {
  checkOverflow()
  window.addEventListener('resize', checkOverflow)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', checkOverflow)
})

</script>
<template>
  <el-popover :disabled="isOverflowHidden" trigger="hover" :width="tooltipWidth">
    <template #reference>
      <div ref="customPopover"
        class="cursor-pointer width-full overflow-hidden whitespace-nowrap text-ellipsis">
        {{ props.strTxt || '--' }}
      </div>
    </template>
    <template #default>
      <div>{{ props.strTxt || '--' }}</div>
    </template>
  </el-popover>
</template>
<style lang="less" scoped></style>
